import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2 as cv

# 读取单张图片
def imgDeal(ii):
    # 读取图片，得出二值图像
    lena = mpimg.imread('data/train/%s.jpg'%(ii)) #40,40,3
    theShape = lena.shape
    lena2 = np.sum(lena,axis=2,keepdims=True)/3
    for i in range(theShape[0]):
        for j in range(theShape[1]):
            if lena2[i,j,0]>200:
                lena2[i,j,0]=0
            else:
                lena2[i,j,0] = 1

    # 寻找出角点坐标
    tempRow = np.zeros(theShape[0])
    tempCollom= np.zeros(theShape[1])
    for i in range(theShape[0]):
        for j in range(theShape[1]):
            if lena2[i,j,0]==1:
                tempRow[i] = tempRow[i]+1
                tempCollom[j] = tempCollom[j]+1
    for i in range(len(tempRow)):
        if tempRow[i]!= 0:
            xStart =i
            for j in range(i,len(tempRow)):
                if tempRow[j]== 0:
                    xEnd = j
                    break
            break
    xStart=xStart-1
    xEnd=xEnd+1
    for i in range(len(tempCollom)):
        if tempCollom[i]!= 0:
            yStart =i
            for j in range(i,len(tempCollom)):
                if tempCollom[j]== 0:
                    yEnd = j
                    break
            break
    yStart = yStart-1
    yEnd = yEnd+1

    # 分成六块，计算百分比
    tempX = (xEnd-xStart)//3
    tempY = (yEnd-yStart)//2
    result = []

    t_1 = 0
    t_0 = 0
    for i in range(xStart,xStart+tempX):
        for j in range(yStart,yStart+tempY):
            if lena2[i,j,0] == 0:
                t_0 = t_0 + 1
            if lena2[i,j,0] == 1:
                t_1 = t_1 +1
    result.append(t_1/(t_1+t_0))

    t_1 = 0
    t_0 = 0
    for i in range(xStart+tempX,xStart+tempX*2):
        for j in range(yStart,yStart+tempY):
            if lena2[i,j,0] == 0:
                t_0 = t_0 + 1
            if lena2[i,j,0] == 1:
                t_1 = t_1 +1
    result.append(t_1/(t_1+t_0))

    t_1 = 0
    t_0 = 0
    for i in range(xStart+tempX*2,xStart+tempX*3):
        for j in range(yStart,yStart+tempY):
            if lena2[i,j,0] == 0:
                t_0 = t_0 + 1
            if lena2[i,j,0] == 1:
                t_1 = t_1 +1
    result.append(t_1/(t_1+t_0))

    t_1 = 0
    t_0 = 0
    for i in range(xStart,xStart+tempX):
        for j in range(yStart+tempY,yStart+tempY*2):
            if lena2[i,j,0] == 0:
                t_0 = t_0 + 1
            if lena2[i,j,0] == 1:
                t_1 = t_1 +1
    result.append(t_1/(t_1+t_0))

    t_1 = 0
    t_0 = 0
    for i in range(xStart+tempX,xStart+tempX*2):
        for j in range(yStart+tempY,yStart+tempY*2):
            if lena2[i,j,0] == 0:
                t_0 = t_0 + 1
            if lena2[i,j,0] == 1:
                t_1 = t_1 +1
    result.append(t_1/(t_1+t_0))
    t_1 = 0
    t_0 = 0
    for i in range(xStart+tempX*2,xStart+tempX*3):
        for j in range(yStart+tempY,yStart+tempY*2):
            if lena2[i,j,0] == 0:
                t_0 = t_0 + 1
            if lena2[i,j,0] == 1:
                t_1 = t_1 +1
    result.append(t_1/(t_1+t_0))
    return result

# 读取图片，得出百分比
dict_precent = {}
for ii in range(1,10):
    result = imgDeal(ii)
    dict_precent[ii]=result

# 计算距离
def knn(result1,result2):
    temp = 0
    for i in range(len(result2)):
        temp = (result1[i]-result2[i])**2+temp
    return temp

# 比对出最佳结果
def judge(jResult):
    theMin = 99999
    theIndex = 0
    for i in range(1,10):
        temp = knn(jResult,dict_precent[i])
        if temp < theMin:
            theMin = temp
            theIndex = i
    return theIndex
# 输入三维数组，得出焦点位置,阈值设置未200
def position(myArray):
    theShape = myArray.shape
    lena2 = np.sum(myArray, axis=2, keepdims=True) / 3

    for i in range(theShape[0]):
        for j in range(theShape[1]):
            if lena2[i, j, 0] > 50:
                lena2[i, j, 0] = 0
            else:
                lena2[i, j, 0] = 1
    plt.imshow(myArray)  # 显示图片
    plt.axis('off')  # 不显示坐标轴
    plt.show()

    tempRow = np.zeros(theShape[0])
    tempCollom = np.zeros(theShape[1])
    for i in range(theShape[0]):
        for j in range(theShape[1]):
            if lena2[i, j, 0] == 1:
                tempRow[i] = tempRow[i] + 1
                tempCollom[j] = tempCollom[j] + 1
    xSE = []
    for i in range(len(tempRow)):
        if tempRow[i] != 0:
            xSE.append(i)
            for j in range(i, len(tempRow)):
                if tempRow[j] == 0:
                    xSE.append(j)
                    break
            break

    print(xSE)

    ySE = []
    for i in range(len(tempCollom)):
        if tempCollom[i] != 0:
            ySE.append(i)
            for j in range(i, len(tempCollom)):
                if tempCollom[j] == 0:
                    ySE.append(j)
                    break
            break
    print(ySE)





cap = cv.VideoCapture(0)
if not cap.isOpened():
    print("Cannot open camera")
    exit()
while True:
    # 逐帧捕获
    ret, frame = cap.read()
    # 如果正确读取帧，ret为True
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    # 我们在框架上的操作到这里
    cv.imshow('frame',frame)
    if cv.waitKey(1) == ord('q'):
        break

# 完成所有操作后，释放捕获器
print(frame.shape)  #(480, 640, 3)
print(type(frame))  #<class 'numpy.ndarray'>
print(frame)
position(frame)

cap.release()
cv.destroyAllWindows()